<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" top="20px" width="900" :close-on-press-escape="false" :close-on-click-modal="false" center>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="job-form">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-form-item label="职位名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入职位名称，如：招聘服务员" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="公司名称" prop="company">
          <el-input v-model="formData.company" placeholder="请输入公司名称" maxlength="50" />
        </el-form-item>

        <el-form-item label="工作类型" prop="jobType">
          <el-select v-model="formData.jobType" placeholder="请选择工作类型" style="width: 100%">
            <el-option label="全职" value="全职" />
            <el-option label="兼职" value="兼职" />
            <el-option label="实习" value="实习" />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资范围" prop="salaryRange">
          <el-input v-model="formData.salaryRange" placeholder="请输入薪资范围，如：3000-5000">
            <template #append>
              <el-button @click="formData.salaryRange = `面议`">面议</el-button>
            </template>
          </el-input>
        </el-form-item>
      </div>

      <!-- 职位要求 -->
      <div class="form-section">
        <h3 class="section-title">职位要求</h3>

        <el-form-item label="学历要求" prop="education">
          <el-select v-model="formData.education" placeholder="请选择学历要求" style="width: 100%">
            <el-option label="不限" value="不限" />
            <el-option label="小学" value="小学" />
            <el-option label="初中" value="初中" />
            <el-option label="高中" value="高中" />
            <el-option label="专科" value="专科" />
            <el-option label="本科" value="本科" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>

        <el-form-item label="工作经验" prop="experience">
          <el-select v-model="formData.experience" placeholder="请选择工作经验要求" style="width: 100%">
            <el-option label="不限" value="不限" />
            <el-option label="应届生" value="应届生" />
            <el-option label="1-3年" value="1-3年" />
            <el-option label="3-6年" value="3-6年" />
            <el-option label="6-10年" value="6-10年" />
            <el-option label="10年以上" value="10年以上" />
          </el-select>
        </el-form-item>

        <el-form-item label="公司福利" prop="tags">
          <div class="tags-input">
            <el-tag v-for="tag in formData.tagsJson" :key="tag" closable @close="removeTag(tag)" class="tag-item">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" class="tag-input" />
            <el-button v-else size="small" @click="showInput">+ 添加福利</el-button>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="100">进行中</el-radio>
            <el-radio :value="200" label="200">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 职位描述 -->
      <div class="form-section">
        <h3 class="section-title">职位描述</h3>
        <el-form-item label="工作职责" prop="responsibilities">
          <el-input v-model="formData.responsibilities" type="textarea" :rows="4" placeholder="如：负责卫生打扫，收拾碗筷，服务顾客" maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="任职要求" prop="requirements">
          <el-input v-model="formData.requirements" type="textarea" :rows="6" placeholder="如：要求会骑车，会电脑，会写自己名字" maxlength="1000" show-word-limit />
        </el-form-item>
      </div>

      <!-- 联系信息 -->
      <div class="form-section">
        <h3 class="section-title">联系信息</h3>
        <el-row v-for="(item, index) in listPhone">
          <el-col :span="12">
            <el-form-item label="联系人" prop="phone" span="12">
              <el-input v-model="item.name" placeholder="姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-input v-model="item.phone" placeholder="联系电话">
              <template #append>
                <el-button @click="handleFormatPhone(item)">格式化</el-button>
              </template>
            </el-input>
          </el-col>
        </el-row>

        <el-form-item label="">
          <div style="cursor: pointer" @click="handleAddPhone">添加联系人</div>
        </el-form-item>

        <el-form-item label="地点名称" prop="addressName">
          <el-input v-model="formData.addressName" placeholder="请输入工作地点，如：玉泰尚城" />
        </el-form-item>
        <el-form-item label="空间坐标" prop="position">
          <el-input v-model="formData.position" placeholder="如：[102.789789,26.456768]">
            <template #append>
              <el-button :icon="Location" @click="handleShowPosition" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="postedDate">
          <el-date-picker type="datetime" v-model="formData.postedDate" placeholder="如：2025-09-10" />
        </el-form-item>

        <el-form-item label="工作地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入工作地点，如：凯通路42号" />
        </el-form-item>

        <el-form-item label="公司头像" v-if="false">
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="handleAvatarUpload">
            <img v-if="formData.face" :src="formData.face" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布职位' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <LocationView ref="refLocationView" @change="handlePositionChange" />
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'
import http from '@/apis/explore'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'

import LocationView from '@/components/location.vue'

import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const refLocationView = ref<typeof LocationView>()

const handleShowPosition = () => {
  // console.log(formData.value.position)
  refLocationView.value?.handleShow(formData.value.position)
}

interface positionType {
  location: string
  lat: number
  lng: number
}
const listPhone = ref<Array<any>>([
  { name: '', phone: '' },
  { name: '', phone: '' }
])

const handleFormatPhone = (obj: any) => {
  obj.phone = obj.phone.replace(/ /g, '').replace(/-/g, '')
}

const handlePositionChange = (obj: positionType) => {
  // console.log(obj)
  formData.value.position = obj.location
}

const user = computed(() => userStore.userInfo)
// console.log(userStore.userInfo)
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

const dialogTitle = ref('新增数据')

// 表单数据
const formData = ref({
  title: '',
  status: 100,
  addressName: '', // 地址名称
  position: '', // 空间位置
  company: '默认公司',
  jobType: '全职',
  tagsJson: ['包吃住'],
  phoneNumbers: '[]',
  location: '东川区',
  postedDate: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
  salaryRange: '3k',
  responsibilities: '',
  requirements: '',
  contactPerson: '',
  phone: '',
  education: '不限',
  experience: '不限',
  face: user.value.avatar || ''
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')

// 状态管理
const submitting = ref(false)

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入职位名称', trigger: 'blur' },
    { min: 2, max: 50, message: '职位名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  jobType: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  salaryRange: [{ required: true, message: '请输入薪资范围', trigger: 'blur' }],
  education: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
  experience: [{ required: true, message: '请选择工作经验要求', trigger: 'change' }]
}

// 添加标签
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleAddPhone = () => {
  let item = {
    name: '',
    phone: ''
  }
  listPhone.value.push(item)
}

const handleInputConfirm = () => {
  if (inputValue.value && !formData.value.tagsJson.includes(inputValue.value)) {
    formData.value.tagsJson.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const removeTag = (tag: string) => {
  const index = formData.value.tagsJson.indexOf(tag)
  if (index > -1) {
    formData.value.tagsJson.splice(index, 1)
  }
}

// 头像上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = (options: any) => {
  // 这里模拟上传，实际项目中需要调用真实的上传接口
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.value.face = e.target?.result as string
  }
  reader.readAsDataURL(options.file)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value,
      tagsJson: ''
    }
    submitData.phoneNumbers = JSON.stringify(listPhone.value)
    submitData.tagsJson = JSON.stringify(formData.value.tagsJson)
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}

const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const dialogVisible = ref(false)
const handleCreate = (obj: any) => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false

  formData.value = {
    title: '',
    status: 100,
    addressName: '', // 地址名称
    position: '', // 空间位置
    company: '默认公司',
    jobType: '全职',
    tagsJson: [],
    phoneNumbers: '[]',
    location: '东川区',
    salaryRange: '3k',
    postedDate: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
    responsibilities: '',
    requirements: '',
    contactPerson: '',
    phone: '',
    education: '不限',
    experience: '不限',
    face: user.value.avatar || ''
  }
  listPhone.value.forEach((t) => {
    t.name = ''
    t.phone = ''
  })
  if (!obj) {
    return
  }

  let tagsJson = []
  if (obj.tagsJson) {
    tagsJson = JSON.parse(obj.tagsJson)
  }
  if (obj.phoneNumbers) {
    listPhone.value = JSON.parse(obj.phoneNumbers)
  }
  formData.value = {
    title: obj.title,
    status: 100,
    phoneNumbers: '[]',
    addressName: obj.addressName, // 地址名称
    position: obj.position, // 空间位置
    company: obj.company,
    jobType: obj.jobType,
    postedDate: dayjs(obj.postedDate).format('YYYY-MM-DD'),
    tagsJson,
    location: obj.location,
    salaryRange: obj.salaryRange,
    responsibilities: obj.responsibilities,
    requirements: obj.requirements,
    contactPerson: obj.contactPerson,
    phone: obj.phone,
    education: obj.education,
    experience: obj.experience,
    face: user.value.avatar || ''
  }
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'

  if (obj.tagsJson) {
    formData.value.tagsJson = JSON.parse(obj.tagsJson)
  }
  if (obj.phoneNumbers) {
    listPhone.value = JSON.parse(obj.phoneNumbers)
  }
  formData.value.postedDate = dayjs(obj.postedDate).format('YYYY-MM-DD')
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
